<template>
  <view class="permission-manager">
    <view class="permission-header">
      <text class="title">权限管理 - {{ roleName }}</text>
    </view>
    
    <view class="permission-content">
      <view v-if="loading" class="loading">
        <uni-load-more status="loading" :content-text="{ contentdown: '加载中...' }"></uni-load-more>
      </view>
      <template v-else>
        <view class="permission-category" v-for="(permissions, category) in groupedPermissions" :key="category">
          <view class="category-header">
            <view class="category-title">{{ category }}</view>
            <view class="category-actions">
              <button size="mini" type="default" @click="selectAllCategory(category)">全选</button>
              <button size="mini" type="default" @click="deselectAllCategory(category)">取消全选</button>
            </view>
          </view>
          
          <view class="permission-list">
            <view class="permission-item" v-for="perm in permissions" :key="perm.id">
              <checkbox :checked="isPermissionSelected(perm.id)" 
                        @change="togglePermission(perm.id)" 
                        :disabled="perm.required" />
              <view class="permission-info">
                <text class="permission-name">{{ perm.name }}</text>
                <text class="permission-code">{{ perm.code }}</text>
                <text class="permission-desc">{{ perm.description }}</text>
              </view>
            </view>
          </view>
        </view>
        
        <view class="permission-actions">
          <button type="primary" @click="savePermissions" :disabled="saving">保存</button>
          <button type="default" @click="cancel">取消</button>
        </view>
      </template>
    </view>
  </view>
</template>

<script>
export default {
  name: 'PermissionManager',
  props: {
    roleId: {
      type: [Number, String],
      required: true
    },
    roleName: {
      type: String,
      default: '未命名角色'
    }
  },
  data() {
    return {
      permissions: [],
      rolePermissions: [],
      loading: true,
      saving: false,
      selectedPermissions: [],
      permissionData: []
    }
  },
  computed: {
    // 按类别分组权限
    groupedPermissions() {
      const groups = {};
      this.permissions.forEach(perm => {
        const category = perm.category || '未分类';
        if (!groups[category]) {
          groups[category] = [];
        }
        groups[category].push(perm);
      });
      return groups;
    }
  },
  created() {
    this.fetchData();
  },
  methods: {
    // 获取所有权限和角色已有权限
    async fetchData() {
      try {
        this.loading = true;
        
        // 获取所有权限
        const allPermsRes = await this.$api.role.getAllPermissions();
        if (allPermsRes.code === 200) {
          this.permissions = allPermsRes.data || [];
        }
        
        // 获取角色已有权限
        const rolePermsRes = await this.$api.role.getRolePermissions(this.roleId);
        if (rolePermsRes.code === 200) {
          this.rolePermissions = rolePermsRes.data || [];
          // 初始化已选权限
          this.selectedPermissions = this.rolePermissions.map(p => p.id);
        }
      } catch (err) {
        uni.showToast({
          title: '获取权限数据失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 检查权限是否被选中
    isPermissionSelected(permId) {
      return this.selectedPermissions.includes(permId);
    },
    
    // 切换权限选择状态
    togglePermission(permId) {
      const index = this.selectedPermissions.indexOf(permId);
      if (index === -1) {
        this.selectedPermissions.push(permId);
      } else {
        this.selectedPermissions.splice(index, 1);
      }
    },
    
    // 全选某个分类下的所有权限
    selectAllCategory(category) {
      const permIds = this.groupedPermissions[category].map(p => p.id);
      this.selectedPermissions = [...new Set([...this.selectedPermissions, ...permIds])];
    },
    
    // 取消全选某个分类下的所有权限
    deselectAllCategory(category) {
      const permIds = this.groupedPermissions[category].map(p => p.id);
      this.selectedPermissions = this.selectedPermissions.filter(id => !permIds.includes(id));
    },
    
    // 保存权限设置
    async savePermissions() {
      try {
        this.saving = true;
        
        // 获取需要添加的权限
        const permissionsToAdd = this.selectedPermissions.filter(
          id => !this.rolePermissions.some(p => p.id === id)
        );
        
        // 获取需要移除的权限
        const permissionsToRemove = this.rolePermissions
          .filter(p => !this.selectedPermissions.includes(p.id))
          .map(p => p.id);
        
        // 添加权限
        for (const permId of permissionsToAdd) {
          await this.$api.role.assignRolePermission({
            roleId: this.roleId,
            permissionId: permId
          });
        }
        
        // 移除权限
        for (const permId of permissionsToRemove) {
          await this.$api.role.revokeRolePermission({
            roleId: this.roleId,
            permissionId: permId
          });
        }
        
        uni.showToast({
          title: '权限设置成功'
        });
        
        this.$emit('saved');
      } catch (err) {
        uni.showToast({
          title: '保存权限设置失败',
          icon: 'none'
        });
      } finally {
        this.saving = false;
      }
    },
    
    // 取消并退出
    cancel() {
      this.$emit('cancel');
    },

    async loadPermissionData() {
      try {
        const res = await this.$api.permission.getData()
        if (res.code === 200) {
          this.permissionData = res.data
        } else {
          uni.showToast({
            title: res.message || '获取权限数据失败',
            icon: 'none'
          })
        }
      } catch (err) {
        uni.showToast({
          title: '获取权限数据失败',
          icon: 'none'
        })
      }
    },
    
    async savePermissionSettings() {
      try {
        const res = await this.$api.permission.saveSettings(this.permissionData)
        if (res.code === 200) {
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          })
        } else {
          uni.showToast({
            title: res.message || '保存权限设置失败',
            icon: 'none'
          })
        }
      } catch (err) {
        uni.showToast({
          title: '保存权限设置失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style lang="scss">
.permission-manager {
  .permission-header {
    padding: 10px 0;
    margin-bottom: 20px;
    border-bottom: 1px solid #eee;
    
    .title {
      font-size: 18px;
      font-weight: bold;
    }
  }
  
  .category-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    background-color: #f8f8f8;
    margin-bottom: 10px;
    
    .category-title {
      font-weight: bold;
    }
    
    .category-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .permission-item {
    display: flex;
    padding: 12px;
    border-bottom: 1px solid #f0f0f0;
    
    .permission-info {
      margin-left: 10px;
      flex: 1;
      
      .permission-name {
        font-weight: bold;
        display: block;
      }
      
      .permission-code {
        font-size: 12px;
        color: #666;
        margin-top: 4px;
        display: block;
      }
      
      .permission-desc {
        font-size: 12px;
        color: #999;
        margin-top: 4px;
        display: block;
      }
    }
  }
  
  .permission-actions {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid #eee;
  }
  
  .loading {
    display: flex;
    justify-content: center;
    padding: 40px 0;
  }
  
  .permission-category {
    margin-bottom: 20px;
  }
}
</style> 